package com.xy.frame.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xy.frame.IConstants;

/**
 * Created by admin on 2014/3/27.
 */
public class AuthorInterceptor extends HandlerInterceptorAdapter {

	Logger logger = LoggerFactory.getLogger(AuthorInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		Object se = request.getSession().getAttribute(IConstants.SESSION_USER);
		logger.info("请求URI:" + request.getRequestURI() + "验证用户Session:" + se);
		if (se == null) {
			if (logger.isDebugEnabled()) {
				logger.debug("用户未登录");
			}
			// 判断是否ajax请求
			boolean isAjax = "XMLHttpRequest".equals(request
					.getHeader("X-Requested-With"));
			
			if (logger.isDebugEnabled()) {
				logger.debug("用户未登录,ajax request "+isAjax);
			}
//			if (isAjax) {
//				String jsstr = "<SCRIPT type=\"text/javascript\">window.location.href=\""
//						+ request.getContextPath() + "/login\";" + "</SCRIPT>";
//				response.setContentType("application/x-javascript");
//				PrintWriter out = response.getWriter();
//				out.print(jsstr);
//				out.flush();
//				out.close();
//				return false;
//			} else {
//				response.sendRedirect(request.getContextPath() + "/login");
//				return false;
//			}
			response.sendRedirect(request.getContextPath() + "/login/timeout");
			return false;
		}
		return true;
	}
}